﻿
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Services.BASE;
using XiangziProjectTemplete.Core.IRepository.Base;
using System.Threading.Tasks;
using XiangziProjectTemplete.Core.Model;
using System.Collections.Generic;
using XiangziProjectTemplete.Core.Model.PostParamModels.XiangziProjectTemplete;
using System.Linq;
using XiangziProjectTemplete.Core.IRepository.UnitOfWork;
using System;
using XiangziProjectTemplete.Core.Model.Globle;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Model.CommonModel;

namespace XiangziProjectTemplete.Core.Services
{
    /// <summary> 
    /// AGV报警服务接口实现 
    /// </summary>	 
    public class Les_AgvWarningServices : BaseServices<Les_AgvWarning>, ILes_AgvWarningServices
    {
        private readonly IBaseRepository<Les_AgvWarning> _dal;
        private readonly IBaseRepository<Les_Agv> _dal_Agv;
        public Les_AgvWarningServices(IBaseRepository<Les_AgvWarning> dal, IBaseRepository<Les_Agv> dal_Agv)
        {
            this._dal_Agv = dal_Agv;
            this._dal = dal;
            base.BaseDal = dal;
        }

        /// <summary>
        /// 处理AGV报警信息
        /// </summary>
        /// <param name="_unitOfWork"></param>
        /// <param name="requestList"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> AddAgvWarning(IUnitOfWork _unitOfWork, List<AgvWarningPostParam> requestList)
        {
            try
            {
                _unitOfWork.BeginTran();//开启事务

                //获取AGV的车辆列表
                List<Les_Agv> agvList = await _dal_Agv.Query();

                //获取现有的报警记录(未消除的)
                List<Les_AgvWarning> dbAgvWarningListForNoFinished = await _dal.Query(x => x.Status == 0);
                List<Les_AgvWarning> needClearWarningList = new List<Les_AgvWarning>();
                foreach (var request in requestList)
                {
                    if (request.error != null && request.error.Count > 0)
                    {
                        foreach (var err in request.error)
                        {
                            var isExist = dbAgvWarningListForNoFinished.Exists(x => x.AgvName == request.name && x.WarningCode == err);
                            if (!isExist)
                            {
                                AgvWarningStatusEnum initAgvWarnStatus = AgvWarningStatusEnum.新建;
                                Les_AgvWarning insert_agvWarning = new Les_AgvWarning()
                                {
                                    Status = Convert.ToInt32(initAgvWarnStatus),
                                    StatusName = initAgvWarnStatus.ToString(),

                                    AgvName = request.name,
                                    AgvNameDesc = "",
                                    WarningTime = DateTime.Now,
                                    WarningCode = err,
                                    WarningContent = Globle.AgvWarningDict[err.ToString()],
                                    WarningLocation = request.currentPosition,

                                    CreateTime = DateTime.Now,
                                    ModifyTime = DateTime.Now,
                                    CreateBy = "AGV",
                                    ModifyBy = "AGV",
                                    OperationRemark = "新增报警"
                                };
                                if (agvList != null && agvList.Count > 0)
                                {
                                    var curAgv = agvList.Find(x => x.AgvName == request.name);
                                    if (curAgv != null) insert_agvWarning.AgvNameDesc = curAgv.AgvNameDesc;
                                }
                                await _dal.Add(insert_agvWarning);
                            }
                        }

                        //寻找 本次请求报警中没有的，但是在数据库中有未完成的报警，就认定为是解警了。
                        needClearWarningList = dbAgvWarningListForNoFinished.Where(x => x.AgvName == request.name && !request.error.Contains(x.WarningCode)).ToList();
                    }
                    else
                    {
                        //寻找 本次请求报警中没有的，但是在数据库中有未完成的报警，就认定为是解警了。
                        needClearWarningList = dbAgvWarningListForNoFinished.Where(x => x.AgvName == request.name).ToList();
                    }

                    //更新这些需要解警的
                    foreach (var needClear in needClearWarningList)
                    {
                        AgvWarningStatusEnum finishAgvWarnStatus = AgvWarningStatusEnum.已处理;
                        needClear.ModifyBy = "AGV";
                        needClear.ModifyTime = DateTime.Now;
                        needClear.OperationRemark = "解警";
                        needClear.Status = Convert.ToInt32(finishAgvWarnStatus);
                        needClear.StatusName = finishAgvWarnStatus.ToString();
                        needClear.FinishTime = DateTime.Now;
                        var msg = "";
                        int seconds = DateTimeHelper.GetTimeDiffer(needClear.WarningTime, needClear.FinishTime, ref msg);
                        needClear.DurationTime = msg;
                        //记录持续时间（分钟）
                        needClear.DurationMinuteTime = Math.Round((decimal)seconds / 60, 2, MidpointRounding.AwayFromZero);

                        await _dal.Update(needClear);
                    }

                }

                _unitOfWork.CommitTran();
            }
            catch (System.Exception)
            {
                _unitOfWork.RollbackTran();
                throw;
            }

            return MessageModel<bool>.Success("成功");
        }

        /// <summary>
        /// 更新报警内容为已读
        /// </summary>
        /// <param name="id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<FunReturnResultModel> UpdateWarningKnow(int id, string user)
        {
            FunReturnResultModel ret = new FunReturnResultModel();
            try
            {
                var data = await _dal.QueryById(id);
                if (data == null)
                {
                    ret = new FunReturnResultModel()
                    {
                        IsSuccess = false,
                        ErrMsg = "没有找到该报警数据！"
                    };
                    return ret;
                }
                data.IsKnow = 1;
                data.ModifyBy = user;
                data.ModifyTime = DateTime.Now;
                data.OperationRemark = "更新报警内容为已读";

                var result = await _dal.Update(data);
                if (result)
                {
                    return new FunReturnResultModel()
                    {
                        IsSuccess = true
                    };
                }
                else
                {
                    ret = new FunReturnResultModel()
                    {
                        IsSuccess = false,
                        ErrMsg = "更新失败！"
                    };
                    return ret;
                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 更新全部报警为已处理
        /// </summary>
        /// <param name="id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<FunReturnResultModel> UpdateAllWarningDone(string user, string content)
        {
            FunReturnResultModel ret = new FunReturnResultModel();
            try
            {
                var datas = await _dal.Query(x => x.Status == 0);
                foreach (var data in datas)
                {
                    data.Status = Convert.ToInt32(AgvWarningStatusEnum.已处理);
                    data.StatusName = AgvWarningStatusEnum.已处理.ToString();
                    data.FinishTime = DateTime.Now;
                    data.CloseContent = content;

                    var msg = "";
                    DateTimeHelper.GetTimeDiffer(data.WarningTime, data.FinishTime, ref msg);
                    data.DurationTime = msg;

                    data.ModifyBy = user;
                    data.ModifyTime = DateTime.Now;
                    data.OperationRemark = "更新全部报警为已处理";

                    data.FinishTime = DateTime.Now;
                    await _dal.Update(data);
                }
                var result = true;
                if (result)
                {
                    return new FunReturnResultModel()
                    {
                        IsSuccess = true
                    };
                }
                else
                {
                    ret = new FunReturnResultModel()
                    {
                        IsSuccess = false,
                        ErrMsg = "更新失败！"
                    };
                    return ret;
                }
            }
            catch
            {
                throw;
            }
        }

    }
}
